import axios from 'axios'
import {Message, MessageBox} from 'element-ui'
import cookie from 'js-cookie'

// 创建axios实例
const service = axios.create({
  baseURL: 'http://localhost:8222', // api的base_url
  timeout: 20000 // 请求超时时间
})
// http request 拦截器
service.interceptors.request.use(
  config => {
    //debugger
    if (cookie.get('we_token')) { //we: wisdom education
      config.headers['token'] = cookie.get('we_token');
    }
    return config
  },
  err => {
    return Promise.reject(err);
  })
// http response 拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 28004) {
      MessageBox('您还未登录, 是否前往登录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log("response.data.resultCode是28004")
        // 返回 错误代码-1 清除ticket信息并跳转到登录页面
        //debugger
        window.location.href = "/login"
      }).catch((response) => {
        if (response === 'cancel') {
          Message.info('已取消')
        }
      })
      //ruten则不弹出自定义异常消息
      return
    }

    if (res.code !== 20000) {
      //25000：订单支付中，不做任何提示
      if (res.code !== 25000) {
        Message({
          message: res.message || 'error',
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject('error')
      }

    } else {
      return response.data
    }

  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
export default service
